package io.github.lee.app.unsplash.ui.search.history

import android.os.Bundle
import androidx.fragment.app.viewModels
import com.chad.library.adapter.base.util.setOnDebouncedItemClick
import dagger.hilt.android.AndroidEntryPoint
import io.github.lee.app.unsplash.R
import io.github.lee.app.unsplash.ui.search.SearchVM
import io.github.lee.core.ui.BaseRefreshFragment

@AndroidEntryPoint
class SearchHistoryFragment : BaseRefreshFragment<SearchHistoryVM>() {

    var searchVM: SearchVM? = null
    private val headerRecent by lazy {
        SearchRecentHeaderAdapter().addOnItemChildClickListener(R.id.tvClear) { _, _, _ ->
            searchVM?.clearAll()
        }

    }


    companion object {
        fun newInstance(): SearchHistoryFragment =
            SearchHistoryFragment()
    }

    //===Desc:======================================================================================
    override fun onCreateViewModel(): SearchHistoryVM =
        viewModels<SearchHistoryVM>().value

    override fun onResume() {
        super.onResume()
        searchVM?.queryCount(10) {
            if (it.isEmpty()) {
                removeAdapter(headerRecent)
                vm?.submitList(emptyList())
            } else {
                addHeaderAdapter(headerRecent)
                vm?.submitList(it)
            }
        }
    }
    //===Desc:======================================================================================

    override fun onInitData(savedInstanceState: Bundle?) {
        super.onInitData(savedInstanceState)
        enableRefresh = false
        enableLoadMore = false
    }


    override fun onSetViewListener() {
        super.onSetViewListener()
        vm?.adapter?.setOnDebouncedItemClick{adapter,_,position->
            val keyword = adapter.items[position]
            searchVM?.searchKeyWord?.set(keyword.keyword)
            searchVM?.saveSearchKeyword()
        }
    }

    override fun onSetViewData() {
        super.onSetViewData()
        recyclerView?.setBackgroundColor(mContext.getColor(R.color.mainBackground))

    }
}